package com.hongru.mms.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Copyright (c) 1998-2022 北京新鸿儒世纪网络技术有限公司 All Rights Reserved.
 * @Url https://www.xinhongru.com
 * @ClassName AliyunSmsUtil
 * @Author salter <salter@vip.163.com>
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2022/1/29 14:34
 */

@Component
public class AliCloudSmsUtil {

    private static String signName;
    private static String accessKeyId;
    private static String accessKeySecret;

    @Value(value = "${jo.sms.alicloud.signName}")
    public void setSignName(String signName) {
        this.signName = signName;
    }

    @Value(value = "${jo.sms.alicloud.accessKeyId}")
    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    @Value(value = "${jo.sms.alicloud.accessKeySecret}")
    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }


    /**
     * 使用AK&SK初始化账号Client
     */
    private static Client createClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public static String sendSms(String cloudCode, String phones, String templateParamJson) {
        try {
            Client client = createClient();
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phones)
                    .setSignName(signName)
                    .setTemplateCode(cloudCode)
                    .setTemplateParam(templateParamJson);
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            return JSONObject.toJSONString(sendSmsResponse.getBody());
        } catch (Exception e) {
            return e.getMessage();
        }
    }

}
